package org.linlinjava.litemall.web.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.core.exception.EncryptionException;
import org.linlinjava.litemall.core.payment.DefaultCurType;
import org.linlinjava.litemall.core.util.AdminCouponDateUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.util.ResponseUtil.Response;
import org.linlinjava.litemall.core.util.paymentCodeUtil.EncryptionUtils;
import org.linlinjava.litemall.db.beans.Constants;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.dto.LitemallAccountBookFormDto;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.OrderUtil;
import org.linlinjava.litemall.web.vo.GiftCardQueryResponseVO;
import org.linlinjava.litemall.web.vo.MemberQueryResponseVO;
import org.linlinjava.litemall.web.vo.WebRechargeOfReceiptVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static org.linlinjava.litemall.web.util.WebResponseCode.*;

/**
 * 礼物卡服务
 *
 * 
 */
@Service
@RequiredArgsConstructor
public class WebGiftCardService {

    private final LitemallGiftCardUserService giftCardService;

	private final LitemallGiftCardUserLogService litemallGiftCardUserLogService;

	private final LitemallGiftCardUserService litemallGiftCardUserService;

	private final LitemallGiftCardService litemallGiftCardService;

	private final LitemallGiftCardOrderService litemallGiftCardOrderService;

	private final LitemallAccountBookService litemallAccountBookService;

	private final LitemallUserService litemallUserService;

	private final LitemallRechargeTransactionsService litemallRechargeTransactionsService;

	private final LumierelLevelMemberService lumierelLevelMemberService;

	private final LumiereCloverPayLogService lumiereCloverPayLogService;

	private final LitemallShopService litemallShopService;

	private final LitemallOrderService litemallOrderService;

	private final LitemallCashScheduleService litemallCashScheduleService;

	private final LumiereCouponStrategyService lumiereCouponStrategyService;

	private final LumiereCouponUserService lumiereCouponUserService;

	private final WebCouponService webCouponService;

    /**
     * 礼物卡查询
     * @param cardNo 卡号
     * @return
     */
   	@Transactional
	public Response<GiftCardQueryResponseVO> query(String cardNo) {
		if(!StringUtils.isNotBlank(cardNo)) {
			return ResponseUtil.badArgument();
		}
		LitemallGiftCardUser result = giftCardService.findByNumber(cardNo);
		if(null == result) {
			return ResponseUtil.badArgument(ORDER_PAY_IS_NULL_CARD, "礼物卡不存在");
		}

		GiftCardQueryResponseVO response = new GiftCardQueryResponseVO();
		BeanUtils.copyProperties(result, response);
		return ResponseUtil.ok(response);
	}


	@Transactional
	public Response<GiftCardQueryResponseVO> recharge(String cardNo, BigDecimal amount, Integer userId, Integer shopId,BigDecimal receiveAmount,String deviceNo) {
		if(!StringUtils.isNotBlank(cardNo)) {
			return ResponseUtil.badArgument();
		}

		if(amount.subtract(BigDecimal.ZERO).compareTo(BigDecimal.ZERO) <= 0){
			return ResponseUtil.fail(INVALID_RECHARGE_AMOUNT,"充值金额不正确");
		}

		LitemallGiftCardUser result = giftCardService.findByNumber(cardNo);
		if(null == result) {
			return ResponseUtil.badArgument(ORDER_PAY_IS_NULL_CARD, "礼物卡不存在");
		}

		BigDecimal availableAmount = result.getAmount().add(amount);
		result.setAmount(availableAmount);
		giftCardService.updateById(result);



		LitemallGiftCardUserLog log = new LitemallGiftCardUserLog();
		log.setAmount(amount);
		log.setAddUserId(result.getUserId());
		log.setType(Constants.LOG_GIFTCARD_RECHARGE);
		log.setCardNumber(result.getCardNumber());
		log.setCardUserId(result.getId());
		log.setContent("充值"+amount);
        log.setOrderSource(Constants.ORDER_SOURCE_POS);
        log.setBalance(result.getAmount());
		log.setChangePoints(BigDecimal.ZERO);
		litemallGiftCardUserLogService.add(log);

		//记录现金交易
		LitemallCashSchedule cashSchedule = LitemallCashSchedule.builder()
				.userId(userId)
				.shopId(shopId)
				.type(2)
				.payTime(LocalDateTime.now())
				.orderCash(amount)
				.receiveCash(receiveAmount)
				.change(receiveAmount.subtract(amount))
				.actualCash(amount)
				.refundCash(BigDecimal.ZERO)
				.deviceNo(deviceNo)
				.build();
		litemallCashScheduleService.save(cashSchedule);

		LitemallUser user = litemallUserService.findById(userId);
		//充值记录
		litemallRechargeTransactionsService.save(new LitemallRechargeTransactions()
				.setUserId(user.getId())
				.setCardNo(cardNo)
				.setShopId(shopId)
				.setUsername(user.getUsername())
				.setRechargeType(Constants.RECHARGE_TYPE_GIFT_CARD)
				.setPayType(Constants.PAY_TYPE_CASH)
				.setRechargeAmount(amount)
				.setRechargeSource(Constants.ORDER_SOURCE_POS)
		);

		//充值策略
		webCouponService.awardCoupon(litemallUserService.findById(result.getUserId()),amount,8,result.getGiftCardId());


		//添加优惠券
		List<LumiereCouponStrategy> couponStrategies = lumiereCouponStrategyService.list(Wrappers.lambdaQuery(LumiereCouponStrategy.class)
				.eq(LumiereCouponStrategy::getCouponType,8)
				.eq(LumiereCouponStrategy::getStatus, 1)
				.le(LumiereCouponStrategy::getRechargeAmount,amount));
		if(couponStrategies!=null&&couponStrategies.size()>0) {
			for (LumiereCouponStrategy lumiereCouponStrategy : couponStrategies) {
				long nextId = IdUtil.getSnowflake(2, 2).nextId();
				LocalDateTime[] localDateTimes = AdminCouponDateUtil.calculateExpirationTime(lumiereCouponStrategy);
				//发放券
				for (int i = 1;i<=lumiereCouponStrategy.getTotal();i++){
					LumiereCouponUser coupon = LumiereCouponUser.builder()
							.userId(userId)
							.strategyId(lumiereCouponStrategy.getId())
							.couponId(lumiereCouponStrategy.getCouponId())
							.userName(result.getUserName())
							.startTime(localDateTimes[0])
							.endTime(localDateTimes[1])
							.code(String.valueOf(nextId))
							.addTime(LocalDateTime.now())
							.updateTime(LocalDateTime.now())
							.deleted(false)
							.build();
					lumiereCouponUserService.save(coupon);
				}
			}
		}
		addAccountBook(shopId,amount,null,0,3);
		GiftCardQueryResponseVO response = new GiftCardQueryResponseVO();
		BeanUtils.copyProperties(result, response);
		return ResponseUtil.ok(response);
	}

	private void addAccountBook(Integer shopId, BigDecimal actualPrice, String remark, Integer recordType, Integer sourceType) {
		LitemallAccountBookFormDto form = new LitemallAccountBookFormDto();
		form.setShopId(shopId);
		form.setRecordType(recordType);
		form.setRecordDate(LocalDateTime.now());
		form.setAmount(actualPrice);
		form.setRemark(remark);
		form.setSourceType(sourceType);
		litemallAccountBookService.create(shopId, form);
	}

	@Transactional
	public synchronized Response rechargeByAmount(String cardNo, BigDecimal amount, String membershipNumber, Integer shopId) {
		if(!StringUtils.isNotBlank(cardNo)) {
			return ResponseUtil.badArgument();
		}
		if(amount.subtract(BigDecimal.ZERO).compareTo(BigDecimal.ZERO) <= 0){
			return ResponseUtil.fail(INVALID_RECHARGE_AMOUNT,"充值金额不正确");
		}
		LitemallGiftCardUser result = giftCardService.findByNumber(cardNo);
		if(null == result) {
			return ResponseUtil.badArgument(ORDER_PAY_IS_NULL_CARD, "礼物卡不存在");
		}
		try {
			membershipNumber=EncryptionUtils.decrypt(membershipNumber);
		}catch (EncryptionException e){
			return ResponseUtil.fail(814,"付款码已过期，请刷新再试");
		} catch (Exception e){
			return ResponseUtil.fail(815,"付款码解析失败");
		}
		//查看用户会员号是否正确
		LitemallUser litemallUser = litemallUserService.getOne(Wrappers.lambdaQuery(LitemallUser.class)
				.eq(LitemallUser::getMembershipNumber, membershipNumber)
				.eq(LitemallUser::getInnerAccount,0));
		if(ObjectUtil.isNull(litemallUser)){
			return ResponseUtil.fail(ORDER_PAY_IS_NULL_MERMEBR,"会员不存在");
		}
		if(litemallUser.getAvailableAmount().compareTo(amount)==-1){
			return ResponseUtil.fail(ORDER_PAY_NOT_ENOUGH_AMOUNT,"余额不足");
		}
		//用户扣余额
		litemallUser.setAvailableAmount(litemallUser.getAvailableAmount().subtract(amount));
		boolean updateAmount = litemallUserService.updateById(litemallUser);
		if(!updateAmount){
			return ResponseUtil.fail(814,"余额扣款失败");
		}
		BigDecimal availableAmount = result.getAmount().add(amount);
		result.setAmount(availableAmount);
		giftCardService.updateById(result);

		LitemallGiftCardUserLog log = new LitemallGiftCardUserLog();
		log.setAmount(amount);
		log.setAddUserId(result.getUserId());
		log.setType(Constants.LOG_GIFTCARD_RECHARGE);
		log.setCardNumber(result.getCardNumber());
		log.setCardUserId(result.getId());
		log.setContent("充值"+amount);
		log.setOrderSource(Constants.ORDER_SOURCE_POS);
		log.setBalance(result.getAmount());
		log.setChangePoints(BigDecimal.ZERO);
		litemallGiftCardUserLogService.add(log);
		addAccountBook(shopId,amount,null,0,3);

		//添加优惠券
		List<LumiereCouponStrategy> couponStrategies = lumiereCouponStrategyService.list(Wrappers.lambdaQuery(LumiereCouponStrategy.class)
				.eq(LumiereCouponStrategy::getCouponType,8)
				.eq(LumiereCouponStrategy::getStatus, 1)
				.le(LumiereCouponStrategy::getRechargeAmount,amount));
		if(couponStrategies!=null&&couponStrategies.size()>0) {
			for (LumiereCouponStrategy lumiereCouponStrategy : couponStrategies) {
				long nextId = IdUtil.getSnowflake(2, 2).nextId();
				LocalDateTime[] localDateTimes = AdminCouponDateUtil.calculateExpirationTime(lumiereCouponStrategy);
				//发放券
				for (int i = 1;i<=lumiereCouponStrategy.getTotal();i++){
					LumiereCouponUser coupon = LumiereCouponUser.builder()
							.userId(result.getUserId())
							.strategyId(lumiereCouponStrategy.getId())
							.couponId(lumiereCouponStrategy.getCouponId())
							.userName(result.getUserName())
							.startTime(localDateTimes[0])
							.endTime(localDateTimes[1])
							.code(String.valueOf(nextId))
							.addTime(LocalDateTime.now())
							.updateTime(LocalDateTime.now())
							.deleted(false)
							.build();
					lumiereCouponUserService.save(coupon);
				}
			}
		}
		GiftCardQueryResponseVO response = new GiftCardQueryResponseVO();
		BeanUtils.copyProperties(result, response);
		return ResponseUtil.ok(response);
	}
	@Transactional
	public Response rechargeByGiftCard(String rechargeCardNo, String payCardNo, BigDecimal amount, Integer shopId) {

		//断言

		Assert.isFalse(!StringUtils.isNotBlank(rechargeCardNo), JSON.toJSONString(ResponseUtil.badArgument()));
		Assert.isFalse(!StringUtils.isNotBlank(payCardNo), JSON.toJSONString(ResponseUtil.badArgument()));
		Assert.isFalse(amount.subtract(BigDecimal.ZERO).compareTo(BigDecimal.ZERO) <= 0, JSON.toJSONString(ResponseUtil.fail(INVALID_RECHARGE_AMOUNT,"充值金额不正确")));
		LitemallGiftCardUser rechargeGiftCard= giftCardService.findByNumber(rechargeCardNo);
		Assert.isFalse(null == rechargeGiftCard, JSON.toJSONString(ResponseUtil.badArgument(ORDER_PAY_IS_NULL_CARD, "礼物卡不存在")));
		LitemallGiftCardUser payGiftCard = giftCardService.findByNumber(payCardNo);
		Assert.isFalse(null == payGiftCard, JSON.toJSONString(ResponseUtil.badArgument(ORDER_PAY_IS_NULL_CARD, "礼物卡不存在")));
		Assert.isFalse(payGiftCard.getAmount().compareTo(amount)==-1, JSON.toJSONString(ResponseUtil.fail(ORDER_PAY_NOT_ENOUGH_AMOUNT,"支付余额不足")));

		/*if(!StringUtils.isNotBlank(rechargeCardNo)) {
			return ResponseUtil.badArgument();
		}
		if(!StringUtils.isNotBlank(payCardNo)) {
			return ResponseUtil.badArgument();
		}
		if(amount.subtract(BigDecimal.ZERO).compareTo(BigDecimal.ZERO) <= 0){
			return ResponseUtil.fail(INVALID_RECHARGE_AMOUNT,"充值金额不正确");
		}
		LitemallGiftCardUser rechargeGiftCard= giftCardService.findByNumber(rechargeCardNo);
		if(null == rechargeGiftCard) {
			return ResponseUtil.badArgument(ORDER_PAY_IS_NULL_CARD, "礼物卡不存在");
		}
		LitemallGiftCardUser payGiftCard = giftCardService.findByNumber(payCardNo);
		if(null == payGiftCard) {
			return ResponseUtil.badArgument(ORDER_PAY_IS_NULL_CARD, "礼物卡不存在");
		}
		if(payGiftCard.getAmount().compareTo(amount)==-1){
			return ResponseUtil.fail(ORDER_PAY_NOT_ENOUGH_AMOUNT,"支付余额不足");
		}*/

		//充值的礼物卡
		BigDecimal availableAmount = rechargeGiftCard.getAmount().add(amount);
		rechargeGiftCard.setAmount(availableAmount);
		giftCardService.updateById(rechargeGiftCard);
		LitemallGiftCardUserLog rechargeLog = new LitemallGiftCardUserLog();
		rechargeLog.setAmount(amount);
		rechargeLog.setAddUserId(rechargeGiftCard.getUserId());
		rechargeLog.setType(Constants.LOG_GIFTCARD_RECHARGE);
		rechargeLog.setCardNumber(rechargeGiftCard.getCardNumber());
		rechargeLog.setCardUserId(rechargeGiftCard.getId());
		rechargeLog.setContent("充值"+amount);
		rechargeLog.setOrderSource(Constants.ORDER_SOURCE_POS);
		rechargeLog.setBalance(rechargeGiftCard.getAmount());
		litemallGiftCardUserLogService.add(rechargeLog);
		addAccountBook(shopId,amount,null,0,3);

		//支付的礼物卡
		BigDecimal payAmount = payGiftCard.getAmount().subtract(amount);
		payGiftCard.setAmount(payAmount);
		giftCardService.updateById(payGiftCard);
		LitemallGiftCardUserLog payLog = new LitemallGiftCardUserLog();
		payLog.setAmount(amount);
		payLog.setAddUserId(payGiftCard.getUserId());
		payLog.setType(Constants.LOG_GIFTCARD_CONSUME);
		payLog.setCardNumber(payGiftCard.getCardNumber());
		payLog.setCardUserId(payGiftCard.getId());
		payLog.setContent("支付"+amount);
		payLog.setOrderSource(Constants.ORDER_SOURCE_POS);
		payLog.setBalance(payGiftCard.getAmount());
		litemallGiftCardUserLogService.add(payLog);
		addAccountBook(shopId,amount,null,1,3);
		GiftCardQueryResponseVO response = new GiftCardQueryResponseVO();
		BeanUtils.copyProperties(rechargeGiftCard, response);
		//添加优惠券
		List<LumiereCouponStrategy> couponStrategies = lumiereCouponStrategyService.list(Wrappers.lambdaQuery(LumiereCouponStrategy.class)
				.eq(LumiereCouponStrategy::getCouponType,8)
				.eq(LumiereCouponStrategy::getStatus, 1)
				.le(LumiereCouponStrategy::getRechargeAmount,amount));
		if(couponStrategies!=null&&couponStrategies.size()>0) {
			for (LumiereCouponStrategy lumiereCouponStrategy : couponStrategies) {
				long nextId = IdUtil.getSnowflake(2, 2).nextId();
				LocalDateTime[] localDateTimes = AdminCouponDateUtil.calculateExpirationTime(lumiereCouponStrategy);
				//发放券
				for (int i = 1;i<=lumiereCouponStrategy.getTotal();i++){
					LumiereCouponUser coupon = LumiereCouponUser.builder()
							.userId(rechargeGiftCard.getUserId())
							.strategyId(lumiereCouponStrategy.getId())
							.couponId(lumiereCouponStrategy.getCouponId())
							.userName(rechargeGiftCard.getUserName())
							.startTime(localDateTimes[0])
							.endTime(localDateTimes[1])
							.code(String.valueOf(nextId))
							.addTime(LocalDateTime.now())
							.updateTime(LocalDateTime.now())
							.deleted(false)
							.build();
					lumiereCouponUserService.save(coupon);
				}
			}
		}
		return ResponseUtil.ok(response);
	}

	@Transactional
	public Response rechargeSaveByClover(String externalId, String paymentId, BigDecimal amount,String cardNo, String cardType,String giftCardNo,String orderId,Integer shopId) {

		LitemallGiftCardUser giftCardUser = giftCardService.findByNumber(giftCardNo);

		//充值礼物卡
		giftCardUser.setAmount(giftCardUser.getAmount().add(amount));
		giftCardService.updateById(giftCardUser);

		//礼物卡订单
		LitemallGiftCardOrder litemallGiftCardOrder = new LitemallGiftCardOrder();
		litemallGiftCardOrder.setGiftCardId(giftCardUser.getGiftCardId());
		litemallGiftCardOrder.setCardNumber(giftCardUser.getCardNumber());
		litemallGiftCardOrder.setUserId(giftCardUser.getUserId());
		litemallGiftCardOrder.setPayType(Constants.ORDER_PAY_TYPE_CLOVER);
		litemallGiftCardOrder.setPayStatus((byte) 2);
		litemallGiftCardOrder.setPayTime(LocalDateTime.now());
		litemallGiftCardOrder.setAmount(amount);
		litemallGiftCardOrder.setCurrency(DefaultCurType.CAD.getType());
		litemallGiftCardOrder.setUpdateTime(LocalDateTime.now());
		litemallGiftCardOrder.setDeleted(false);
		litemallGiftCardOrder.setShopId(shopId);
		litemallGiftCardOrder.setAddUserId(giftCardUser.getUserId());
		litemallGiftCardOrder.setMessage("Clover Recharge Gift Card at POS");
		litemallGiftCardOrderService.save(litemallGiftCardOrder);

		//礼物卡充值记录
		LitemallGiftCardUserLog giftCardUserLog = new LitemallGiftCardUserLog();
		giftCardUserLog.setAmount(amount);
		giftCardUserLog.setOrderId(litemallGiftCardOrder.getId());
		giftCardUserLog.setAddUserId(giftCardUser.getUserId());
		giftCardUserLog.setType(Constants.LOG_GIFTCARD_RECHARGE);
		giftCardUserLog.setCardNumber(giftCardUser.getCardNumber());
		giftCardUserLog.setCardUserId(giftCardUser.getId());
		giftCardUserLog.setContent("Clover recharge"+giftCardNo);
		giftCardUserLog.setOrderSource(Constants.ORDER_SOURCE_POS);
		giftCardUserLog.setBalance(giftCardUser.getAmount());
		litemallGiftCardUserLogService.add(giftCardUserLog);
		addAccountBook(shopId,amount,null,0,3);

		//clover支付记录
		LumiereCloverPayLog cloverPayLog = new LumiereCloverPayLog();
		cloverPayLog.setExternalId(externalId);
		cloverPayLog.setCardNo(cardNo);
		cloverPayLog.setPaymentId(paymentId);
		cloverPayLog.setCardType(cardType);
		cloverPayLog.setAddTime(LocalDateTime.now());
		cloverPayLog.setUpdateTime(LocalDateTime.now());
		cloverPayLog.setDeleted(false);
		cloverPayLog.setOrderId(orderId);
		lumiereCloverPayLogService.add(cloverPayLog);

		LitemallUser user = litemallUserService.findById(giftCardUser.getUserId());

		//充值记录
		litemallRechargeTransactionsService.save(new LitemallRechargeTransactions()
				.setUserId(user.getId())
				.setCardNo(cardNo)
				.setShopId(shopId)
				.setUsername(user.getUsername())
				.setRechargeType(Constants.RECHARGE_TYPE_GIFT_CARD)
				.setPayType(Constants.PAY_TYPE_CLOVER)
				.setRechargeAmount(amount)
				.setRechargeSource(Constants.ORDER_SOURCE_POS)
		);

		//充值策略
		webCouponService.awardCoupon(litemallUserService.findById(giftCardUser.getUserId()),amount,8,giftCardUser.getGiftCardId());
		//添加优惠券
		List<LumiereCouponStrategy> couponStrategies = lumiereCouponStrategyService.list(Wrappers.lambdaQuery(LumiereCouponStrategy.class)
				.eq(LumiereCouponStrategy::getCouponType,8)
				.eq(LumiereCouponStrategy::getStatus, 1)
				.le(LumiereCouponStrategy::getRechargeAmount,amount));
		if(couponStrategies!=null&&couponStrategies.size()>0) {
			for (LumiereCouponStrategy lumiereCouponStrategy : couponStrategies) {
				long nextId = IdUtil.getSnowflake(2, 2).nextId();
				LocalDateTime[] localDateTimes = AdminCouponDateUtil.calculateExpirationTime(lumiereCouponStrategy);
				//发放券
				for (int i = 1;i<=lumiereCouponStrategy.getTotal();i++){
					LumiereCouponUser coupon = LumiereCouponUser.builder()
							.userId(giftCardUser.getUserId())
							.strategyId(lumiereCouponStrategy.getId())
							.couponId(lumiereCouponStrategy.getCouponId())
							.userName(giftCardUser.getUserName())
							.startTime(localDateTimes[0])
							.endTime(localDateTimes[1])
							.code(String.valueOf(nextId))
							.addTime(LocalDateTime.now())
							.updateTime(LocalDateTime.now())
							.deleted(false)
							.build();
					lumiereCouponUserService.save(coupon);
				}
			}
		}
		GiftCardQueryResponseVO response = new GiftCardQueryResponseVO();
		BeanUtils.copyProperties(giftCardUser, response);
		return ResponseUtil.ok(response);
	}

	public Response findGiftOrUser(String code) {
		if(!StringUtils.isNotBlank(code)) {
			return ResponseUtil.badArgument();
		}
		//识别礼物卡
		LitemallGiftCardUser cardUser = giftCardService.findByNumber(code);
		if(null != cardUser) {
			GiftCardQueryResponseVO response = new GiftCardQueryResponseVO();
			BeanUtils.copyProperties(cardUser, response);
			response.setType(2);
			return ResponseUtil.ok(response);
		}else {
			//先识别会员码
			try {
				code=EncryptionUtils.decrypt(code);
			}catch (EncryptionException e){
				return ResponseUtil.fail(814,"付款码已过期，请刷新再试");
			} catch (Exception e){
				return ResponseUtil.fail(815,"付款码有误解析失败");
			}
			List<LitemallUser> users = litemallUserService.queryByCondition(code);
			if(!CollectionUtils.isEmpty(users)) {
				MemberQueryResponseVO response = new MemberQueryResponseVO();
				BeanUtils.copyProperties(users.get(0), response);
				//查询等级会员名称
				LumiereLevelMember levelMember = lumierelLevelMemberService.findById(response.getUserLevel().intValue());
				response.setLevelMember(ObjectUtil.isNotNull(levelMember)?levelMember.getName():"No membership level");
				response.setMembershipNumber(code);
				response.setType(1);
				return ResponseUtil.ok(response);
			}
		}
		return ResponseUtil.badArgument();
	}

	public Response rechargeOfReceipt(Integer shopId, Integer userId,Integer type, String cardNo, String deviceNo, String membershipNumber, BigDecimal amount, BigDecimal cash,String cloverNo) throws Exception {
		LitemallShop shop = litemallShopService.findById(shopId);
		Integer todayMaxSerialNo = litemallOrderService.getTodayMaxSerialNo(shopId);
		WebRechargeOfReceiptVO rechargeOfReceipt = null;
		if(null == cash){
			rechargeOfReceipt =WebRechargeOfReceiptVO.builder()
					.shopName("LUMIERE CAFE")
					.storeNo(shop.getName())
					.shopAddress(shop.getStreetAddress())
					.shopMobile(shop.getMobile())
					.serialNo(todayMaxSerialNo)
					.payDate(new SimpleDateFormat("dd/MM/yyyy").format(new Date()))
					.payTime(new SimpleDateFormat("hh:mm:ssa", Locale.ENGLISH).format(new Date()))
					.id(userId)
					.pos(deviceNo)
					.register("4")
					.amount(amount)
					.type(type)
					.build();
		}else{
			rechargeOfReceipt =WebRechargeOfReceiptVO.builder()
					.shopName("LUMIERE CAFE")
					.storeNo(shop.getName())
					.shopAddress(shop.getStreetAddress())
					.shopMobile(shop.getMobile())
					.serialNo(todayMaxSerialNo)
					.payDate(new SimpleDateFormat("dd/MM/yyyy").format(new Date()))
					.payTime(new SimpleDateFormat("hh:mm:ssa", Locale.ENGLISH).format(new Date()))
					.id(userId)
					.pos(deviceNo)
					.register("4")
					.amount(amount)
					.cash(cash)
					.change(cash.subtract(amount))
					.type(type)
					.build();
		}

		if(type==1){
			//现金充值礼物卡
			LitemallGiftCardUser giftCardUser = litemallGiftCardUserService.findByNumber(cardNo);
			LitemallGiftCard giftCard = litemallGiftCardService.findById(giftCardUser.getGiftCardId());
			rechargeOfReceipt.setGiftCardNumber(giftCardUser.getCardNumber());
			rechargeOfReceipt.setName(giftCard.getName());
			rechargeOfReceipt.setBalance(giftCardUser.getAmount().subtract(amount));
			rechargeOfReceipt.setTotalBalance(giftCardUser.getAmount());
			rechargeOfReceipt.setPayType(1);
		}else if(type==2){
			//现金充值账户余额
			LitemallUser user = litemallUserService.queryByCondition(membershipNumber).get(0);
			rechargeOfReceipt.setUsername(user.getUsername());
			rechargeOfReceipt.setName(user.getNickname());
			rechargeOfReceipt.setBalance(user.getAvailableAmount().subtract(amount));
			rechargeOfReceipt.setTotalBalance(user.getAvailableAmount());
			rechargeOfReceipt.setPayType(1);
		}else if(type==3){
			//clover充值余额
			LitemallUser user = litemallUserService.queryByCondition(membershipNumber).get(0);
			rechargeOfReceipt.setUsername(user.getUsername());
			rechargeOfReceipt.setName(user.getNickname());
			rechargeOfReceipt.setBalance(user.getAvailableAmount().subtract(amount));
			rechargeOfReceipt.setTotalBalance(user.getAvailableAmount());
			rechargeOfReceipt.setCloverNo(cloverNo);
			rechargeOfReceipt.setPayType(5);
		}else if(type==4){
			//clover充值礼物卡
			LitemallGiftCardUser giftCardUser = litemallGiftCardUserService.findByNumber(cardNo);
			LitemallGiftCard giftCard = litemallGiftCardService.findById(giftCardUser.getGiftCardId());
			rechargeOfReceipt.setGiftCardNumber(giftCardUser.getCardNumber());
			rechargeOfReceipt.setName(giftCard.getName());
			rechargeOfReceipt.setBalance(giftCardUser.getAmount().subtract(amount));
			rechargeOfReceipt.setTotalBalance(giftCardUser.getAmount());
			rechargeOfReceipt.setCloverNo(cloverNo);
			rechargeOfReceipt.setPayType(5);
		}else if(type==5){
			//余额充值礼物卡
			LitemallGiftCardUser giftCardUser = litemallGiftCardUserService.findByNumber(cardNo);
			LitemallGiftCard giftCard = litemallGiftCardService.findById(giftCardUser.getGiftCardId());
			rechargeOfReceipt.setGiftCardNumber(giftCardUser.getCardNumber());
			rechargeOfReceipt.setName(giftCard.getName());
			rechargeOfReceipt.setBalance(giftCardUser.getAmount().subtract(amount));
			rechargeOfReceipt.setTotalBalance(giftCardUser.getAmount());
			rechargeOfReceipt.setPayType(4);
		}else if(type==6){
			//礼物卡充值余额
			LitemallUser user = litemallUserService.queryByCondition(membershipNumber).get(0);
			LitemallGiftCardUser giftCardUser = litemallGiftCardUserService.findByNumber(cardNo);
			rechargeOfReceipt.setUsername(user.getUsername());
			rechargeOfReceipt.setName(user.getNickname());
			rechargeOfReceipt.setBalance(giftCardUser.getAmount().subtract(amount));
			rechargeOfReceipt.setTotalBalance(giftCardUser.getAmount());
			rechargeOfReceipt.setGiftCardNumber(giftCardUser.getCardNumber());
			rechargeOfReceipt.setPayType(2);
		}else if(type==7){
			//礼物卡充值礼物卡
			LitemallGiftCardUser giftCardUser = litemallGiftCardUserService.findByNumber(cardNo);
			LitemallGiftCard giftCard = litemallGiftCardService.findById(giftCardUser.getGiftCardId());
			rechargeOfReceipt.setGiftCardNumber(giftCardUser.getCardNumber());
			rechargeOfReceipt.setName(giftCard.getName());
			rechargeOfReceipt.setBalance(giftCardUser.getAmount().subtract(amount));
			rechargeOfReceipt.setTotalBalance(giftCardUser.getAmount());
			rechargeOfReceipt.setPayType(2);
		}
		return ResponseUtil.ok(rechargeOfReceipt);
	}



}

